package com.orhonit.ipb.portal.rest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.ag.core.context.BaseContextHandler;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.orhonit.ipb.portal.biz.BaseUserExtensionBiz;
import com.orhonit.ipb.portal.biz.EducationCodeBiz;
import com.orhonit.ipb.portal.biz.JoApplyJoinPartyBiz;
import com.orhonit.ipb.portal.biz.JoJoinInfoBiz;
import com.orhonit.ipb.portal.biz.JoStatusTimeBiz;
import com.orhonit.ipb.portal.biz.TbPartyMemberBaseInfoBiz;
import com.orhonit.ipb.portal.biz.TbPartyOrgBaseInfoBiz;
import com.orhonit.ipb.portal.biz.TbPartyOrgCatalogBiz;
import com.orhonit.ipb.portal.biz.TbPmEducationExperienceBiz;
import com.orhonit.ipb.portal.biz.WorkflowServer;
import com.orhonit.ipb.portal.configuration.UploadConfigTemp;
import com.orhonit.ipb.portal.entity.BaseUserExtension;
import com.orhonit.ipb.portal.entity.EducationCode;
import com.orhonit.ipb.portal.entity.JoApplyJoinParty;
import com.orhonit.ipb.portal.entity.JoJoinInfo;
import com.orhonit.ipb.portal.entity.JoStatusTime;
import com.orhonit.ipb.portal.entity.TbPartyOrgBaseInfo;
import com.orhonit.ipb.portal.entity.TbPartyOrgCatalog;
import com.orhonit.ipb.portal.entity.TbPmEducationExperience;
import com.orhonit.ipb.security.auth.client.annotation.CheckUserToken;
import com.orhonit.ipb.security.common.rest.BaseController;
import com.orhonit.ipb.security.common.util.UUIDUtils;

import net.sf.json.JSONObject;

@RestController
@RequestMapping("user")
public class BaseUserExtensionController extends BaseController<BaseUserExtensionBiz,BaseUserExtension> {
    @Autowired
	private BaseUserExtensionBiz baseUserExtensionBiz;
    @Autowired
    private TbPmEducationExperienceBiz tbPmEducationExperienceBiz;
    @Autowired
    private TbPartyMemberBaseInfoBiz tbPartyMemberBaseInfoBiz;
    @Autowired
	private UploadConfigTemp uploadConfig;
    @Autowired
    private JoJoinInfoBiz joinInfoBiz;
    @Autowired
    private JoApplyJoinPartyBiz joApplyJoinPartyBiz;
    @Autowired
    private WorkflowServer workflowServer;
    @Autowired
    private JoStatusTimeBiz joStatusTimeBiz;
    @Autowired
    private TbPartyOrgCatalogBiz tbPartyOrgCatalogBiz;
    @Autowired
   	private TbPartyOrgBaseInfoBiz tbPartyOrgBaseInfoBiz;
    @Autowired
    private EducationCodeBiz educationCodeBiz;
    /**
     * 获取当前用户信息self
     * @return
     */
	@RequestMapping(value = "/getbaseUserInfoImageByself", method = RequestMethod.GET)
	@CheckUserToken
	public void getbaseUserInfoImageByself(HttpServletResponse response){
		String userId =BaseContextHandler.getUserID();
//		String userId="89c75217-86af-4e62-bc11-37eb63bd273f";
		BaseUserExtension baseUserExtension=baseUserExtensionBiz.getBaseUserExtensionByuserId(userId);
		//return ResultUtil.toResponseWithData(ResultCode.SUCCESS, baseUserExtension);
		try {
			 if(StringUtils.isNotBlank(baseUserExtension.getHeadPortrait())){
					
				 OutputStream os;
				 File file=new File(baseUserExtension.getHeadPortrait());
				 InputStream imageStream = new FileInputStream(file);  
				 response.setContentType("image/png");
				 response.setContentType("image/jpg");
				 os = response.getOutputStream();
				 int bytesRead = 0;
				 byte[] buffer = new byte[8192];
				 while ((bytesRead = imageStream.read(buffer, 0, 8192)) != -1) {
					 os.write(buffer, 0, bytesRead);
				 }
				 os.close();
				 imageStream.close();
				}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 获取学历列表
	 * @return
	 */
	@RequestMapping(value = "/getEducationcode", method = RequestMethod.GET)
	public ResponseEntity<?> getEducationcode(){
		List<EducationCode> list=educationCodeBiz.getEducationCodes();
		 return ResponseEntity.ok(list);
	}
    /**
     * 获取当前用户信息self
     * @return
     */
	@RequestMapping(value = "/getbaseUserInfoByself", method = RequestMethod.GET)
	@CheckUserToken
	public ResponseEntity<?> getbaseUserInfoByself(){
		String userId =BaseContextHandler.getUserID();
//		String userId="89c75217-86af-4e62-bc11-37eb63bd273f";
		BaseUserExtension baseUserExtension=baseUserExtensionBiz.getBaseUserExtensionByuserId(userId);
		//return ResultUtil.toResponseWithData(ResultCode.SUCCESS, baseUserExtension);
		 return ResponseEntity.ok(baseUserExtension);
		 
	}
	/**
	 * 获取教育经历self
	 * @return
	 */
	@RequestMapping(value = "/getEducationExperienceByself", method = RequestMethod.GET)
	@CheckUserToken
	public ResponseEntity<?> getEducationExperienceByself(){
		String userId =BaseContextHandler.getUserID();
//		String userId="89c75217-86af-4e62-bc11-37eb63bd273f";
		List<TbPmEducationExperience> list=tbPmEducationExperienceBiz.getTbPmEducationExperienceByuserId(userId);
		 return ResponseEntity.ok(list);
	}
	/**
	 * 添加基本信息 启动流程
	 * @param file 照片
	 * @param userinfo 基础信息json 其中 organizationname为code
	 * @param education 教育经历 json table= tb_pm_education_experience
	 * @param joinInfo 专业技能，文体特长 json table=jo_join_info
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/savebaseUserInfo",  method = RequestMethod.POST,consumes = "multipart/form-data")
	@CheckUserToken
	public ResponseEntity<?> savebaseUserInfo(@RequestParam("file") MultipartFile file,String userinfo,String education,String joinInfo) throws IllegalStateException, IOException{
		String userId =BaseContextHandler.getUserID();
		/**上传头像*/
//		String userId ="89c75217-86af-4e62-bc11-37eb63bd273f";
		long time = System.currentTimeMillis();  
		File filePath = new File(uploadConfig.getPath());//  /api/admin/portal/userInfo/
		String imageurl=time+file.getOriginalFilename();
		if (null != file && file.getSize() > 0) {
		filePath.mkdirs();
		filePath = new File(filePath+File.separator+imageurl);
		file.transferTo(filePath);
		}
		Gson gson = new Gson();
		//json 转BaseUserExtension对象
		BaseUserExtension baseUserExtension = gson.fromJson(userinfo, new TypeToken<BaseUserExtension>() {
		}.getType());
		baseUserExtension.setHeadPortrait(imageurl);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("placePartyBranch", baseUserExtension.getOrganizationname());
		
		//json 转List<TbPmEducationExperience>
		List<TbPmEducationExperience> list = gson.fromJson(education, new TypeToken<List<TbPmEducationExperience>>() {
		}.getType());
		//可能时间格式文体需要完善
		for(int i=0;i<list.size();i++){
			list.get(i).setId((int)System.currentTimeMillis()+i);
			list.get(i).setIdCardNumber(baseUserExtension.getIdCardNumber());
		}
		JoApplyJoinParty joApplyJoinParty=new JoApplyJoinParty();
		joApplyJoinParty.setId(UUIDUtils.generateUuid());
		joApplyJoinParty.setUserId(userId);
		joApplyJoinParty.setParentUserId(baseUserExtension.getOrganizationname());
		joApplyJoinParty.setCreateTime(new Date());
		joApplyJoinParty.setStatus(1);	
		String deptid=tbPartyOrgCatalogBiz.getTbPartyOrgCatalogByDeptId(joApplyJoinParty.getParentUserId());
		TbPartyOrgBaseInfo temp1=tbPartyOrgBaseInfoBiz.getTbPartyOrgBaseInfoBypOrganizationCode(deptid);
		String deptid2=tbPartyOrgCatalogBiz.getTbPartyOrgCatalogByDeptId(deptid);
		TbPartyOrgBaseInfo temp2=tbPartyOrgBaseInfoBiz.getTbPartyOrgBaseInfoBypOrganizationCode(deptid2);
		joApplyJoinParty.setUpdeptid(temp1.getPOrganizationCode());
		joApplyJoinParty.setUpupdeptid(temp2.getPOrganizationCode());
		joApplyJoinPartyBiz.insertSelective(joApplyJoinParty);//保存
		JSONObject jsonObj = JSONObject.fromObject(joinInfo);
		String label = jsonObj.getString("label");
		String value = jsonObj.optString("value");
		JoJoinInfo joinInfos =new JoJoinInfo();
		/*JoJoinInfo joinInfos = gson.fromJson(joinInfo, new TypeToken<JoJoinInfo>() {
		}.getType());*/
		joinInfos.setId(UUIDUtils.generateUuid());
		joinInfos.setJoinId(joApplyJoinParty.getId());
		joinInfos.setLabel(label);
		joinInfos.setValue(value);
		joinInfoBiz.insertSelective(joinInfos);//保存
		JoStatusTime joStatusTime=new JoStatusTime();
		joStatusTime.setId(UUIDUtils.generateUuid());
		joStatusTime.setApplyId(joApplyJoinParty.getId());
		joStatusTime.setApply(new Date());
		joStatusTimeBiz.insertSelective(joStatusTime);
		/**更新基本信息*/
		baseUserExtensionBiz.updateBaseUserExtension(baseUserExtension);
		/**更新所在支部*/
		boolean update=tbPartyMemberBaseInfoBiz.updateTbPartyMemberBaseInfoDeptByUserId(map);
		boolean insert=tbPmEducationExperienceBiz.BatchInsertTbPmEducationExperience(list);
		if(update==true&&insert==true){
			workflowServer.startVac(userId,joApplyJoinParty.getId());//启动流程
			return ResponseEntity.ok(null);
		}
		else{
			return ResponseEntity.status(401).body("网络异常");
		}
		
		
	}
	
	
	
	/**
     * 获取用户基本信息
     * @return
     */
	@RequestMapping(value = "/getbaseUserInfo", method = RequestMethod.GET)
	public ResponseEntity<?> getbaseUserInfo(String userId){
		BaseUserExtension baseUserExtension=baseUserExtensionBiz.getBaseUserExtensionByuserId(userId);
		 return ResponseEntity.ok(baseUserExtension);
	}
	/**
	 * 获取教育经历
	 * @return
	 */
	@RequestMapping(value = "/getEducationExperience", method = RequestMethod.GET)
	public ResponseEntity<?> getEducationExperienceBiz(String userId){
		List<TbPmEducationExperience> list=tbPmEducationExperienceBiz.getTbPmEducationExperienceByuserId(userId);
		 return ResponseEntity.ok(list);
	}
	/**
	 * 通过组织id 查找孩子节点  status 0:该下无组织；1：改下有组织
	 * @return
	 */
	@RequestMapping(value = "/getChildrenDept", method = RequestMethod.GET)
	public ResponseEntity<?> getTbPartyOrgCatalogByparentId(String DeptId){
		if("0".equals(DeptId)){
			List<TbPartyOrgCatalog> list=new ArrayList<TbPartyOrgCatalog>();
			TbPartyOrgCatalog a=tbPartyOrgCatalogBiz.getrootId();
			list.add(a);
			return ResponseEntity.ok(list);
		}
		else{
			List<TbPartyOrgCatalog> list=tbPartyOrgCatalogBiz.getTbPartyOrgCatalogByparentId(DeptId);
			 return ResponseEntity.ok(list);
		}
		
	}
	
}